package com.example.demo.http;

import com.alibaba.fastjson2.JSON;
import okhttp3.*;

import java.net.URI;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author calwen
 * @since 2023/12/28
 */
public class OkhttpUtil {
    private static volatile OkHttpClient okHttpClient = null;

    public OkhttpUtil() {
        ConnectionPool pool = new ConnectionPool(3, 120, TimeUnit.SECONDS);
        okHttpClient = new OkHttpClient.Builder()
                .connectionPool(pool)
                .build();
    }

    public static OkHttpClient getClient() {
        if (okHttpClient == null) {
            synchronized (OkhttpUtil.class) {
                if (okHttpClient == null) {
                    okHttpClient = new OkHttpClient();
                }
            }
        }
        return okHttpClient;
    }

    public Object syncPost(URI uri, Map<String, Object> headers, Object body) throws Exception {
        String bodyStr = (body != null) ? JSON.toJSONString(body) : "{}";
        Request.Builder requestBuilder = new Request.Builder()
                .url(uri.toURL())
                .post(RequestBody.create(MediaType.parse("application/json"), bodyStr));
        if (headers != null) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue().toString());
            }
        }
        Request request = requestBuilder.build();
        try (Response response = getClient().newCall(request).execute()) {
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                System.out.println("Response: " + responseBody);
            } else {
                System.out.println("Error: " + response.code() + " " + response.message());
            }
        }
        return "request";
    }

}
